package com.joe.codemother.parser;

import com.joe.codemother.ai.model.MultiFileCodeResult;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MultiCodeParser implements CodeParser<MultiFileCodeResult> {

    private static final Pattern HTML_CODE_PATTERN = Pattern.compile("```html\\s*\\n([\\s\\S]*?)```", Pattern.CASE_INSENSITIVE);
    private static final Pattern CSS_CODE_PATTERN = Pattern.compile("```css\\s*\\n([\\s\\S]*?)```", Pattern.CASE_INSENSITIVE);
    private static final Pattern JS_CODE_PATTERN = Pattern.compile("```(?:js|javascript)\\s*\\n([\\s\\S]*?)```", Pattern.CASE_INSENSITIVE);

    @Override
    public MultiFileCodeResult parseCode(String content) {
        MultiFileCodeResult result = new MultiFileCodeResult();
        String html = this.extractMultiPart(content,HTML_CODE_PATTERN);
        String css = this.extractMultiPart(content,CSS_CODE_PATTERN);
        String js = this.extractMultiPart(content,JS_CODE_PATTERN);
        if(html != null && html.length() > 0) {
            result.setHtmlCode(html);
        }
        if(css != null && css.length() > 0) {
            result.setCssCode(css);
        }
        if(js != null && js.length() > 0) {
            result.setJsCode(js);
        }
        return result;
    }

    private String extractMultiPart(String content, Pattern pattern) {
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }
}
